package com.anita.member.service;


import com.anita.member.domain.service.JwtService;
import com.anita.member.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

/**
 * JWT服务实现类
 * 将JwtUtil包装为领域服务实现
 */
@Service
public class JwtServiceImpl implements JwtService {
    
    private final JwtUtil jwtUtil;
    
    public JwtServiceImpl(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }
    
    @Override
    public String generateAccessToken(UserType userType, Long userId) {
        JwtUtil.UserType utilUserType = convertToUtilUserType(userType);
        return jwtUtil.generateAccessToken(utilUserType, userId);
    }
    
    @Override
    public String generateRefreshToken(UserType userType, Long userId) {
        JwtUtil.UserType utilUserType = convertToUtilUserType(userType);
        return jwtUtil.generateRefreshToken(utilUserType, userId);
    }
    
    @Override
    public boolean validateAccessToken(String token) {
        return jwtUtil.validateAccessToken(token);
    }
    
    @Override
    public boolean validateRefreshToken(String token) {
        return jwtUtil.validateRefreshToken(token);
    }
    
    @Override
    public Claims parseAccessToken(String token) {
        return jwtUtil.parseAccessToken(token);
    }
    
    @Override
    public Claims parseRefreshToken(String token) {
        return jwtUtil.parseRefreshToken(token);
    }
    
    @Override
    public Long getUserIdFromClaims(Claims claims) {
        return jwtUtil.getUserIdFromClaims(claims);
    }
    
    @Override
    public UserType getUserTypeFromClaims(Claims claims) {
        JwtUtil.UserType utilUserType = jwtUtil.getUserTypeFromClaims(claims);
        return convertFromUtilUserType(utilUserType);
    }
    
    /**
     * 转换用户类型：领域枚举 -> 工具枚举
     */
    private JwtUtil.UserType convertToUtilUserType(UserType userType) {
        return switch (userType) {
            case ADMIN -> JwtUtil.UserType.ADMIN;
            case MEMBER -> JwtUtil.UserType.MEMBER;
        };
    }
    
    /**
     * 转换用户类型：工具枚举 -> 领域枚举
     */
    private UserType convertFromUtilUserType(JwtUtil.UserType utilUserType) {
        return switch (utilUserType) {
            case ADMIN -> UserType.ADMIN;
            case MEMBER -> UserType.MEMBER;
            default -> throw new IllegalArgumentException("未知的用户类型: " + utilUserType);
        };
    }
}